import axios, { type AxiosResponse } from 'axios'
import store from 'store'

const service = axios.create({
  baseURL: import.meta.env.MODE === 'development' ? '/_api' : import.meta.env.VITE_APP_API_BASE_URL,
  headers: {
      'tenant-id': '1',
      'Content-Type': 'application/json;charset=UTF-8',
  },
})

service.interceptors.request.use(
  (config) => {
    const token = store.get('token')
    if (token)
      config.headers.Authorization = `Bearer ${token}`
    return config
  },
  (error) => {
    return Promise.reject(error.response)
  },
)

service.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => {
    if (response.status === 200)
      return response.data

    throw new Error(response.status.toString())
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default service
